package com.attrisoft.sanger.demo;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.attrisoft.sanger.aws.S3Client;

public class Workflow implements Runnable{
    
    private static Map<String,List<String>> current = new HashMap<String,List<String>>();
    
    private String user;
    private String name;
    private String email;
    private File reference;
    private File sample;
    private String pre;
    private String inflation;
    
    public static String getName(String name) {
        return name.trim().replace(' ', '-');
    }
    
    public static boolean exists(String user, String name) {
        List<String> flows = current.get(user);
        return flows == null ? false : flows.contains(getName(name));
    }
    
    public static List<String> getCurrent(String user) {
        List<String> flows = current.get(user);
        return flows != null ? flows : new ArrayList<String>();
    }
    
    private static void remove(String user, String name) {
        current.get(user).remove(name);
    }
    
    private static void add(String user, String name) {
        List<String> flows = current.get(user);
        if (flows == null) {
            flows = new ArrayList<String>();
            current.put(user, flows);
        }
        flows.add(name);
    }
    
    public Workflow(String user, String name, String email, File reference, File sample, String pre, String inflation) {
        this.user = user;
        this.name = getName(name);
        this.email = email;
        this.reference = reference;
        this.sample = sample;
        this.pre = pre;
        this.inflation = inflation;
    }

    public void run() {
        add(user, name);
        try {
            File dir = new File("workflow" +File.separator +user +File.separator +name);
            dir.mkdirs();
            reference.renameTo(new File(dir, reference.getName()));
            sample.renameTo(new File(dir, sample.getName()));
            String cmd = "../../../src/main/shell/process.sh"
                    + " " +sample.getName()
                    + " " +reference.getName()
                    + " " +pre
                    + " " +inflation;
            System.err.println("###### Running: " +cmd);
            Process proc = Runtime.getRuntime().exec(cmd, new String[0], dir);
            proc.waitFor();
            System.err.println("###### Got: " +proc.exitValue());
            remove(user, name);
            File input = new File(dir.getAbsolutePath() +File.separator +"input");
            File output = new File(dir.getAbsolutePath() +File.separator +"output");
            S3Client.createWorkflow(user, name, input.listFiles(), output.listFiles());
            Mailer.send(email, "Workflow [" +name +"] complete", 
                new File(dir.getAbsolutePath() +File.separator +"output" +File.separator +"process.log"),
                new File(dir.getAbsolutePath() +File.separator +"output" +File.separator +"timings.log"));
            remove(dir);
        } catch (Exception e) {
            e.printStackTrace();
            Mailer.send(email, "Workflow [" +name +"] failed", e.getMessage());
            remove(user, name);
        }
    }
    
    private static boolean remove(File directory) {
        if (directory == null)
            return false;
        if (!directory.exists())
            return true;
        if (!directory.isDirectory())
            return false;
        String[] list = directory.list();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                File entry = new File(directory, list[i]);
                if (entry.isDirectory()) {
                    if (!remove(entry))
                        return false;
                } else {
                    if (!entry.delete())
                        return false;
                }
            }
        }
        return directory.delete();
    }
}
